//
//  HYPDFPreviewController.m
//  XPlayer
//
//  Created by 张水 on 2023/9/19.
//

#import "HYPDFPreviewController.h"
#import <PDFKit/PDFKit.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "HYRequestBaseHelper.h"

@interface HYPDFPreviewController ()<PDFDocumentDelegate>

@property (nonatomic, strong) PDFView *pdfView;

@property (nonatomic, strong) PDFDocument *pdfDocument;

@end

@implementation HYPDFPreviewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = self.fileName;
    self.view.backgroundColor = AppBgThemeColor;
    self.navigationBarView.navagationBarStyle = Left_button_Show;
    [self configUI];
    [self previewInternet];
}

-(void)configUI
{
    self.pdfView = [[PDFView alloc] initWithFrame:CGRectZero];
    self.pdfView.autoScales = YES;
    self.pdfView.userInteractionEnabled = YES;
    [self.view addSubview:self.pdfView];
    [self.pdfView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.navigationBarView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view.mas_bottom);
        }
    }];
}

// 预览网络文件
- (void)previewInternet {
    //判断是否存在
    if([self isFileExist:self.fileName]) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:self.fileName];
        [self preViewFile:url];
    }else {
        NSDictionary *dic = [NSDictionary dictionaryWithObject:@"pan.baidu.com" forKey:@"User-Agent"];
        [HYHub loadMessage:NSLocalizedString(@"加载数据中", nil)];
        NSURLSessionDownloadTask *downloadTask = [HYRequestBaseHelper download:self.urlString parameters:nil headers:dic progress:^(NSProgress *downloadProgress) {
            NSLog(@"当前下载进度为:%lf", 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:self.fileName];
            return url;
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            if(response){
               [HYHub dismiss];
               [self preViewFile:filePath];
            }else{
                [HYHub showMessage:NSLocalizedString(@"加载失败", nil)];
                [HYHub dismiss];
            }

        }];
        [downloadTask resume];
    }
}

- (void)preViewFile:(NSURL *)url {
    NSData *data = [NSData dataWithContentsOfURL:url];
    self.pdfDocument = [[PDFDocument alloc] initWithData:data];
    self.pdfDocument.delegate = self;
    self.pdfView.document = self.pdfDocument;
}
//判断文件是否已经在沙盒中存在
-(BOOL)isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}

@end
